Disclaimer: Zum Teil basiert dieses Script auf dem Datacamp-Kurs “Working with Data in the Tidyverse”

Introduction to R

Eine Übersicht über gängige Basis-Funktionen bietet der BaseR-CheatSheet: http://github.com/rstudio/cheatsheets/raw/master/base-r.pdf

R as a calculator

2+2
## [1] 4
4*3
## [1] 12
12.5/pi
## [1] 3.978874
3^5
## [1] 243
2+3*6
## [1] 20
(2+3)*6
## [1] 30

In R everything is an object

x <- 5
y <- 12
x+y
## [1] 17
x*y
## [1] 60
z <- x+y
z
## [1] 17

Vectors

l1 <- c(x^1,x^2,x^3,x^4,x^5)
l2 <- c(y*1,y*2,y*3,y*4,y*5)

l1 + l2
## [1]   17   49  161  673 3185

Functions

Eine Funktion bereits gesehen. “c()” Funktionen sind bereits vorgefertigte “Miniprogramme”, manchmal aber auch sehr einfache, die mit einem bestimmten Objekt etwas bestimmtes tun.

Bsp: c(): Concatenate = Verknüpfen: Die Elemente innerhalb der Klammer, werden miteinander kombiniert und zu einem Vektor zusammengefasst.

Andere Beispiele sind bestimmte mathematische Funktionen, wie Mittelwert oder Standardabweichung. Beinahe alles in R wird durch Funktionen erledigt. Eine Funktion ist immer zusammen gesetzt aus dem Namen und den Eingabeparametern innerhalb von Klammern. Gibt es keine Eingabeparameter wird die Klammer leer - aber nicht weg - gelassen.

summary(l1)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##       5      25     125     781     625    3125
var(l1)
## [1] 1780680
sd(l1)
## [1] 1334.421
sum(l1)
## [1] 3905
mean(l2)
## [1] 36
round(3.63545234123, digits = 4)
## [1] 3.6355
plot(l1)

plot(c(5,25,2123,123,5345),l2)

In R können auch ganz einfach eigene Funktionen geschrieben werden. Hilfe gibt es hier: https://www.datacamp.com/community/tutorials/functions-in-r-a-tutorial Zu allen Funktionen gibt es eine Hilfe, welche die möglichen Optionen (arguments) und die grundsätzliche Funktionsweise der Funktion beschreibt. ACHTUNG: Ohne Klammern hinter der Funktion, über die man Infos haben will.

help(sd)
?sd
?summary

Only numbers?

Bisher hatten wir nur Zahlen in unseren Beispielen. In R ist es aber auch möglich (und meistens unproblematisch) mit anderen Datentypen - wie bspw. Text oder Ja/Nein-Zuständen - zu arbeiten.

Text

Inhalte mit Text wird meist in Anführungsstriche oder Hochkommata gesetzt. Die Klasse dieses Objekts ist dann automatisch character

txt <- "Das ist ein Text"
txt
## [1] "Das ist ein Text"
class(txt)
## [1] "character"

Boolean/Logical

Manchmal bietet es sich an nur “Wahr” oder “Falsch” als eigenen Datentypen zu nutzen. Die Schlüsselwörter hier sind TRUE und FALSE. Immer das ganze Wort großgeschrieben. Oftmals wird diese Klasse dafür genutzt Zustände abzufragen, bspw. ob etwas größer ist, ob der Inhalt übereinstimmt etc:

WAHRODERFALSCH <- FALSE
class(WAHRODERFALSCH)
## [1] "logical"
isTRUE(WAHRODERFALSCH)
## [1] FALSE
3 > 5
## [1] FALSE
ist3groesser5 <- 3 > 5
"Ist das ein Text" == txt
## [1] FALSE

Integer und Float-Variablen

Zurück zu Zahlen: Bei Zahlen in R gibt es Unterschiede, ob die Zahl eine “Ganzzahl” (integer) oder eine Zahl mit Nachkommastellen (numeric) ist. Normalerweise ist der Unterschied in R egal und man kann mit beiden Typen identisch arbeiten. Es kann aber Fälle geben, in denen man den Typ bewusst ändern muss.

is.integer(3.541)
## [1] FALSE
is.integer(3)
## [1] FALSE
class(3)
## [1] "numeric"
integer3 <- as.integer(3)
is.integer(integer3)
## [1] TRUE
class(3.654)
## [1] "numeric"

Factor

Bei der Arbeit mit Surveys kommen außerdem häufig noch factors for. Faktoren werden verwendet, um kategorische Daten darzustellen. Faktoren können geordnet oder ungeordnet sein und sind eine wichtige Klasse für statistische Analysen und zum Plotten.

Faktoren werden als Ganzzahlen gespeichert und diesen eindeutigen Ganzzahlen sind Beschriftungen zugeordnet. Während Faktoren wie Zeichenvektoren aussehen (und sich oft verhalten), sind sie tatsächlich in Wirklichkeit ganze Zahlen. Manchmal führt das zu Problemen, wenn man sie wie strings/character behandelt.

education <- factor(c("low", "high", "medium", "high", "low", "medium", "high"))
levels(education)
## [1] "high"   "low"    "medium"
education
## [1] low    high   medium high   low    medium high  
## Levels: high low medium
education <- factor(education, levels = c("low", "medium", "high"))
levels(education)
## [1] "low"    "medium" "high"
min(education) # doesn't work
## Error in Summary.factor(structure(c(1L, 3L, 2L, 3L, 1L, 2L, 3L), .Label = c("low", : 'min' not meaningful for factors
education <- factor(education, levels = c("low", "medium", "high"), ordered = TRUE)
levels(education)
## [1] "low"    "medium" "high"
min(education) # works!
## [1] low
## Levels: low < medium < high

verschiedene Datentypen in einer Tabelle

Fügt man unterschiedliche Datentypen zusammen, so ist der Unterschied zwischen einer matrix und einem data.frame wichtig (siehe nächstes Kapitel). Während in einer matrix nur Elemente des gleichen Datentyps vorhanden sein können, sind bei einem data.frame auch unterschiedliche erlaubt.

numbers <- c(1,2,31,43,5,16)
txt <- c("a","b","oma","uni","zwei Wörter","z")
logical <- c(FALSE,TRUE,FALSE,FALSE,TRUE,FALSE)
factors <- factor(c("low", "high", "medium", "high", "low", "medium"))

tabelle <- cbind(numbers,txt,logical,factors) 
## zum verbinden von Spalten (column-bind); zum verbinden von Zeilen rbind() (row-bind)
tabelle #Man sieht, alle Datentypen wurden zu "Texten" gemacht. Anführungsstriche sind um die Werte herum.
##      numbers txt           logical factors
## [1,] "1"     "a"           "FALSE" "2"    
## [2,] "2"     "b"           "TRUE"  "1"    
## [3,] "31"    "oma"         "FALSE" "3"    
## [4,] "43"    "uni"         "FALSE" "1"    
## [5,] "5"     "zwei Wörter" "TRUE"  "2"    
## [6,] "16"    "z"           "FALSE" "3"
class(tabelle) # R hat die Tabelle automatisch zur Matrix gemacht und deshalb alle Datentypen "gleich" gemacht.
## [1] "matrix"
tabelle2 <- data.frame(numbers,txt,logical,factors, stringsAsFactors = FALSE)
tabelle2
##   numbers         txt logical factors
## 1       1           a   FALSE     low
## 2       2           b    TRUE    high
## 3      31         oma   FALSE  medium
## 4      43         uni   FALSE    high
## 5       5 zwei Wörter    TRUE     low
## 6      16           z   FALSE  medium
class(tabelle2)
## [1] "data.frame"
class(tabelle2$txt)
## [1] "character"
class(tabelle2$numbers)
## [1] "numeric"
# Im Data.frame, sind alle Datentypen erhalten.

Data Frames

Normalerweise haben wir als Datenwissenschaftler aber selten einzelne Rechnungen oder Vektoren, sondern Tabellen mit Zeilen als Beobachtungen und Spalten als Variablen. Diese werden in R als Data Frames dargestellt (oder als Matrix, aber mit dataframes ist es meistens einfacher zu arbeiten).

data.frame(l1,l2)
##     l1 l2
## 1    5 12
## 2   25 24
## 3  125 36
## 4  625 48
## 5 3125 60
df <- data.frame(l1,l2)
df
##     l1 l2
## 1    5 12
## 2   25 24
## 3  125 36
## 4  625 48
## 5 3125 60

Einzelne Elemente des df lassen sich über eckige Klammern hinter dem Objektnamen auswählen. Dabei ist die erste Zahl die Nummer der Zeile und die zweite Zahl die Nummer der Spalte. Durch weglassen einer Zahl, wird entweder die ganze Zeile oder die ganze Spalte ausgegeben.

df[3,2]
## [1] 36
df[ ,2]
## [1] 12 24 36 48 60
df[3, ]
##    l1 l2
## 3 125 36
df[4,5]
## NULL

Variablen (Spalten) lassen sich auch durch den Namen anwählen, indem hinter den Objektnamen ein $ geschrieben wird. RStudio schlägt einem dann meist sogar eine Liste vor, aus der man auswählen kann. Wiederrum kann man durch eckige Klammern, einzelne oder mehrere Elemente auswählen.

summary(df)
##        l1             l2    
##  Min.   :   5   Min.   :12  
##  1st Qu.:  25   1st Qu.:24  
##  Median : 125   Median :36  
##  Mean   : 781   Mean   :36  
##  3rd Qu.: 625   3rd Qu.:48  
##  Max.   :3125   Max.   :60
summary(df$l1)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##       5      25     125     781     625    3125
df$l2
## [1] 12 24 36 48 60
df$l1[3]
## [1] 125
df$l2[4]
## [1] 48
df$l1[1:3]
## [1]   5  25 125
df$l1[1:2]
## [1]  5 25
df$l1[-c(3,5)]
## [1]   5  25 625

Durch logische Operatoren lassen sich so bestimmte Zeilen suchen/ausschließen. So könnte man beispielsweise einen Datensatz mit mehreren Ländern so bearbeiten, dass am Ende nur ein Land heraus käme. Oder nur Menschen über 55 Jahre im Datensatz enthalten sind etc.

df
##     l1 l2
## 1    5 12
## 2   25 24
## 3  125 36
## 4  625 48
## 5 3125 60
df[df$l1>100, ]
##     l1 l2
## 3  125 36
## 4  625 48
## 5 3125 60

Gesprochen: Der Datensatz df und alle Spalten (Hinter dem Komma ist leer). Aber nur die Zeilen, wo in Spalte 1 (l1) Werte über 100 stehen.

Daten einlesen

Die einfachste Art Daten einzulesen ist, wenn sie als einfach “Text-Datei” vorliegen. Beispielsweise .CSV (comma-separated-values), oder anderweitige Formate mit einem eindeutigen Symbol als Trennzeichen für Spalten.

Aber auch andere Formate lassen sich in R einlesen, nur braucht man hierzu meistens zusätzliche Pakete und Funktionen.

Aus csv-Dateien

Im amerikanischen Raum wird die csv-Datei mit Kommata als Spaltentrennzeichen und dem Punkt als Dezimalzeichen bei Zahlen verwendet. Im europäischen Raum wird meistens das Semikolon als Spaltentrennzeichen und das Komma als Dezimalzeichen genutzt. In R wurden deshalb 2 Arten von CSV-Einlese-Funktionen implementiert. read.csv für den amerikanischen Raum und read.csv2 für den europäischen. Die Funktionen lassen sich aber über die Optionen (arguments) anpassen.

read.csv(file = "datensatz_grades.csv", sep = ";", dec = ",")
##    id     name semester Note.P1 Note.P2 Note.P3 gesamt
## 1   1      Mia        3     2.3     2.0     2.7    2.4
## 2   2     Emma        5     2.3     1.3     2.0    2.0
## 3   3    Sofia        9     1.7     1.7     1.7    1.7
## 4   4   Hannah        3     1.7     5.0     1.3    1.8
## 5   5   Emilia       11     2.3     2.3     2.3    2.3
## 6   6     Anna        9     1.3     1.0     1.3    1.2
## 7   7    Marie        9     2.3     1.0     1.7    1.8
## 8   8     Mila        7     1.7     1.0     1.7    1.6
## 9   9     Lina        3     3.3     2.7     5.0    4.0
## 10 10      Lea        9     1.0     2.0     1.3    1.2
## 11 11     Lena        5     1.3     2.3     1.7    1.6
## 12 12   Leonie        3     3.0     1.3     1.7    2.1
## 13 13   Amelie        3     1.7     1.7     1.3    1.5
## 14 14    Luisa        7     2.0     1.0     2.0    1.9
## 15 15 Giuliana       11     1.7     1.0     1.3    1.4
## 16 16   Gloria       11     1.7     2.0     2.3    2.0
## 17 17     Ines       11     2.3     1.0     1.7    1.8
## 18 18      Joy       11     2.7     2.0     3.0    2.7
## 19 19  Youssef        9     2.3     2.3     3.0    2.6
## 20 20  Domenik        9     2.0     5.0     2.3    2.4
## 21 21  Etienne        7     2.7     2.3     1.7    2.1
## 22 22    Jarno        5     2.3     1.7     1.7    1.9
## 23 23   Marian        3     1.7     1.3     1.7    1.6
## 24 24    Mason       11     2.0     1.3     1.7    1.7
## 25 25   Ragnar        7     2.3     1.7     2.0    2.0
## 26 26    Rayan        3     1.7     2.0     5.0    3.3
## 27 27    Semih        7     2.3     2.0     2.0    2.1
read.csv2(file = "datensatz_grades.csv")
##    id     name semester Note.P1 Note.P2 Note.P3 gesamt
## 1   1      Mia        3     2.3     2.0     2.7    2.4
## 2   2     Emma        5     2.3     1.3     2.0    2.0
## 3   3    Sofia        9     1.7     1.7     1.7    1.7
## 4   4   Hannah        3     1.7     5.0     1.3    1.8
## 5   5   Emilia       11     2.3     2.3     2.3    2.3
## 6   6     Anna        9     1.3     1.0     1.3    1.2
## 7   7    Marie        9     2.3     1.0     1.7    1.8
## 8   8     Mila        7     1.7     1.0     1.7    1.6
## 9   9     Lina        3     3.3     2.7     5.0    4.0
## 10 10      Lea        9     1.0     2.0     1.3    1.2
## 11 11     Lena        5     1.3     2.3     1.7    1.6
## 12 12   Leonie        3     3.0     1.3     1.7    2.1
## 13 13   Amelie        3     1.7     1.7     1.3    1.5
## 14 14    Luisa        7     2.0     1.0     2.0    1.9
## 15 15 Giuliana       11     1.7     1.0     1.3    1.4
## 16 16   Gloria       11     1.7     2.0     2.3    2.0
## 17 17     Ines       11     2.3     1.0     1.7    1.8
## 18 18      Joy       11     2.7     2.0     3.0    2.7
## 19 19  Youssef        9     2.3     2.3     3.0    2.6
## 20 20  Domenik        9     2.0     5.0     2.3    2.4
## 21 21  Etienne        7     2.7     2.3     1.7    2.1
## 22 22    Jarno        5     2.3     1.7     1.7    1.9
## 23 23   Marian        3     1.7     1.3     1.7    1.6
## 24 24    Mason       11     2.0     1.3     1.7    1.7
## 25 25   Ragnar        7     2.3     1.7     2.0    2.0
## 26 26    Rayan        3     1.7     2.0     5.0    3.3
## 27 27    Semih        7     2.3     2.0     2.0    2.1
daten <- read.csv2(file = "datensatz_grades.csv")

Dateien aus Stata oder SPSS

Daten von anderen statistischen Sprachen lassen sich meist mit dem Paket foreign einlesen und auch in diesen Formaten abspeichern.

#install.packages(c("openxlsx","foreign"))
library(foreign)

read.spss("datensatz_grades.sav")
## re-encoding from UTF-8
## $id
##  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
## [24] 24 25 26 27
## 
## $name
##  [1] "Mia     " "Emma    " "Sofia   " "Hannah  " "Emilia  " "Anna    "
##  [7] "Marie   " "Mila    " "Lina    " "Lea     " "Lena    " "Leonie  "
## [13] "Amelie  " "Luisa   " "Giuliana" "Gloria  " "Ines    " "Joy     "
## [19] "Youssef " "Domenik " "Etienne " "Jarno   " "Marian  " "Mason   "
## [25] "Ragnar  " "Rayan   " "Semih   "
## 
## $semester
##  [1]  3  5  9  3 11  9  9  7  3  9  5  3  3  7 11 11 11 11  9  9  7  5  3
## [24] 11  7  3  7
## 
## $NoteP1
##  [1] 2.3 2.3 1.7 1.7 2.3 1.3 2.3 1.7 3.3 1.0 1.3 3.0 1.7 2.0 1.7 1.7 2.3
## [18] 2.7 2.3 2.0 2.7 2.3 1.7 2.0 2.3 1.7 2.3
## 
## $NoteP2
##  [1] 2.0 1.3 1.7 5.0 2.3 1.0 1.0 1.0 2.7 2.0 2.3 1.3 1.7 1.0 1.0 2.0 1.0
## [18] 2.0 2.3 5.0 2.3 1.7 1.3 1.3 1.7 2.0 2.0
## 
## $NoteP3
##  [1] 2.7 2.0 1.7 1.3 2.3 1.3 1.7 1.7 5.0 1.3 1.7 1.7 1.3 2.0 1.3 2.3 1.7
## [18] 3.0 3.0 2.3 1.7 1.7 1.7 1.7 2.0 5.0 2.0
## 
## $gesamt
##  [1] 2.4 2.0 1.7 1.8 2.3 1.2 1.8 1.6 4.0 1.2 1.6 2.1 1.5 1.9 1.4 2.0 1.8
## [18] 2.7 2.6 2.4 2.1 1.9 1.6 1.7 2.0 3.3 2.1
## 
## attr(,"label.table")
## attr(,"label.table")$id
## NULL
## 
## attr(,"label.table")$name
## NULL
## 
## attr(,"label.table")$semester
## NULL
## 
## attr(,"label.table")$NoteP1
## NULL
## 
## attr(,"label.table")$NoteP2
## NULL
## 
## attr(,"label.table")$NoteP3
## NULL
## 
## attr(,"label.table")$gesamt
## NULL
## 
## attr(,"codepage")
## [1] 65001
## attr(,"variable.labels")
## named character(0)
read.dta("datensatz_grades.dta")
##    id     name semester Note_P1 Note_P2 Note_P3 gesamt
## 1   1      Mia        3     2.3     2.0     2.7    2.4
## 2   2     Emma        5     2.3     1.3     2.0    2.0
## 3   3    Sofia        9     1.7     1.7     1.7    1.7
## 4   4   Hannah        3     1.7      NA     1.3    1.8
## 5   5   Emilia       11     2.3     2.3     2.3    2.3
## 6   6     Anna        9     1.3     1.0     1.3    1.2
## 7   7    Marie        9     2.3     1.0     1.7    1.8
## 8   8     Mila        7     1.7     1.0     1.7    1.6
## 9   9     Lina        3     3.3     2.7     5.0    4.0
## 10 10      Lea        9     1.0     2.0     1.3    1.2
## 11 11     Lena        5     1.3     2.3     1.7    1.6
## 12 12   Leonie        3     3.0     1.3     1.7    2.1
## 13 13   Amelie        3     1.7     1.7     1.3    1.5
## 14 14    Luisa        7     2.0     1.0     2.0    1.9
## 15 15 Giuliana       11     1.7     1.0     1.3    1.4
## 16 16   Gloria       11     1.7     2.0     2.3    2.0
## 17 17     Ines       11     2.3     1.0     1.7    1.8
## 18 18      Joy       11     2.7     2.0     3.0    2.7
## 19 19  Youssef        9     2.3     2.3     3.0    2.6
## 20 20  Domenik        9     2.0      NA     2.3    2.4
## 21 21  Etienne        7     2.7     2.3     1.7    2.1
## 22 22    Jarno        5     2.3     1.7     1.7    1.9
## 23 23   Marian        3     1.7     1.3     1.7    1.6
## 24 24    Mason       11     2.0     1.3     1.7    1.7
## 25 25   Ragnar        7     2.3     1.7     2.0    2.0
## 26 26    Rayan        3     1.7     2.0     5.0    3.3
## 27 27    Semih        7     2.3     2.0     2.0    2.1

Aus Excel-Dateien

Zunächst einmal ist es möglich aus Excel heraus auch CSV-Dateien zu speichern. Arbeitet man also selber erst mit Excel und will seine Daten dann in R einlesen, ist es meistens einfacher, die Datei direkt als CSV zu speichern. Hat man aber eine xlsx-Datei so kann man diese mit den Paketen xlsx oder openxlsx einlesen.

library(openxlsx)
grades <- read.xlsx('datensatz_grades.xlsx', sheet = 1)
grades
##    id     name semester Note.P1 Note.P2 Note.P3 gesamt
## 1   1      Mia        3     2.3     2.0     2.7    2.4
## 2   2     Emma        5     2.3     1.3     2.0    2.0
## 3   3    Sofia        9     1.7     1.7     1.7    1.7
## 4   4   Hannah        3     1.7     5.0     1.3    1.8
## 5   5   Emilia       11     2.3     2.3     2.3    2.3
## 6   6     Anna        9     1.3     1.0     1.3    1.2
## 7   7    Marie        9     2.3     1.0     1.7    1.8
## 8   8     Mila        7     1.7     1.0     1.7    1.6
## 9   9     Lina        3     3.3     2.7     5.0    4.0
## 10 10      Lea        9     1.0     2.0     1.3    1.2
## 11 11     Lena        5     1.3     2.3     1.7    1.6
## 12 12   Leonie        3     3.0     1.3     1.7    2.1
## 13 13   Amelie        3     1.7     1.7     1.3    1.5
## 14 14    Luisa        7     2.0     1.0     2.0    1.9
## 15 15 Giuliana       11     1.7     1.0     1.3    1.4
## 16 16   Gloria       11     1.7     2.0     2.3    2.0
## 17 17     Ines       11     2.3     1.0     1.7    1.8
## 18 18      Joy       11     2.7     2.0     3.0    2.7
## 19 19  Youssef        9     2.3     2.3     3.0    2.6
## 20 20  Domenik        9     2.0     5.0     2.3    2.4
## 21 21  Etienne        7     2.7     2.3     1.7    2.1
## 22 22    Jarno        5     2.3     1.7     1.7    1.9
## 23 23   Marian        3     1.7     1.3     1.7    1.6
## 24 24    Mason       11     2.0     1.3     1.7    1.7
## 25 25   Ragnar        7     2.3     1.7     2.0    2.0
## 26 26    Rayan        3     1.7     2.0     5.0    3.3
## 27 27    Semih        7     2.3     2.0     2.0    2.1

The Tidyverse

The tidyverse is a coherent system of packages for data manipulation, exploration and visualization that share a common design philosophy. These were mostly developed by Hadley Wickham himself, but they are now being expanded by several contributors. Tidyverse packages are intended to make statisticians and data scientists more productive by guiding them through workflows that facilitate communication, and result in reproducible work products. Fundamentally, the tidyverse is about the connections between the tools that make the workflow possible.

the dplyr-package and the grammar behind

pipes in R

Statt komplizierte Klammerstrukturen zu nutzen oder nach jedem Schritt das Objekt neu abzuspeichern, ist es durch das magittr-package möglich sogenannte pipes zu nutzen. Durch das dplyr-Paket wurden pipes zu einer besonderen Innovation und ändern den workflow in R. Oft wird dadurch der Code sehr viel einfacher lesbar. Durch eine pipe (%>%) lassen sich Ergebnisse aus dem einen Befehl, direkt in den nächsten “überführen”.

Beispiel

s1 <- 3+6
s2 <- exp(s1)
s3 <- round(s2, 3)
s4 <- s3 > 1000

# oder

t <- round(exp((3+6)),3) > 1000

# unkomplizierter

u <- (3+6) %>% 
  exp() %>% 
  round(.,3) > 1000

the filter verb

logical operators “==” nicht “=” aus gapminder wird nichts entfernt, sondern der filter nur onscreen ausgegeben Inhalt mit Text mit Anführungsstrichen

Multiple conditions mit Komma

gapminder[gapminder$year==2007, ]
## # A tibble: 142 x 6
##    country     continent  year lifeExp       pop gdpPercap
##    <fct>       <fct>     <int>   <dbl>     <int>     <dbl>
##  1 Afghanistan Asia       2007    43.8  31889923      975.
##  2 Albania     Europe     2007    76.4   3600523     5937.
##  3 Algeria     Africa     2007    72.3  33333216     6223.
##  4 Angola      Africa     2007    42.7  12420476     4797.
##  5 Argentina   Americas   2007    75.3  40301927    12779.
##  6 Australia   Oceania    2007    81.2  20434176    34435.
##  7 Austria     Europe     2007    79.8   8199783    36126.
##  8 Bahrain     Asia       2007    75.6    708573    29796.
##  9 Bangladesh  Asia       2007    64.1 150448339     1391.
## 10 Belgium     Europe     2007    79.4  10392226    33693.
## # ... with 132 more rows
gapminder %>% 
  filter(year == 2007)
## # A tibble: 142 x 6
##    country     continent  year lifeExp       pop gdpPercap
##    <fct>       <fct>     <int>   <dbl>     <int>     <dbl>
##  1 Afghanistan Asia       2007    43.8  31889923      975.
##  2 Albania     Europe     2007    76.4   3600523     5937.
##  3 Algeria     Africa     2007    72.3  33333216     6223.
##  4 Angola      Africa     2007    42.7  12420476     4797.
##  5 Argentina   Americas   2007    75.3  40301927    12779.
##  6 Australia   Oceania    2007    81.2  20434176    34435.
##  7 Austria     Europe     2007    79.8   8199783    36126.
##  8 Bahrain     Asia       2007    75.6    708573    29796.
##  9 Bangladesh  Asia       2007    64.1 150448339     1391.
## 10 Belgium     Europe     2007    79.4  10392226    33693.
## # ... with 132 more rows
gapminder %>% 
  filter(country == "United States")
## # A tibble: 12 x 6
##    country       continent  year lifeExp       pop gdpPercap
##    <fct>         <fct>     <int>   <dbl>     <int>     <dbl>
##  1 United States Americas   1952    68.4 157553000    13990.
##  2 United States Americas   1957    69.5 171984000    14847.
##  3 United States Americas   1962    70.2 186538000    16173.
##  4 United States Americas   1967    70.8 198712000    19530.
##  5 United States Americas   1972    71.3 209896000    21806.
##  6 United States Americas   1977    73.4 220239000    24073.
##  7 United States Americas   1982    74.6 232187835    25010.
##  8 United States Americas   1987    75.0 242803533    29884.
##  9 United States Americas   1992    76.1 256894189    32004.
## 10 United States Americas   1997    76.8 272911760    35767.
## 11 United States Americas   2002    77.3 287675526    39097.
## 12 United States Americas   2007    78.2 301139947    42952.
gapminder %>% 
  filter(year == 2007, country == "United States")
## # A tibble: 1 x 6
##   country       continent  year lifeExp       pop gdpPercap
##   <fct>         <fct>     <int>   <dbl>     <int>     <dbl>
## 1 United States Americas   2007    78.2 301139947    42952.

the select verb

Select specific variables (columns) by name. No need for complicated counting or concatenating by with c() and square brackets. You can select ranges of variables using “:”. Use the “-” to drop columns. You can change the order, in which the variables appear in the data frame. You can also select and renaming variables at the same time.

gapminder
## # A tibble: 1,704 x 6
##    country     continent  year lifeExp      pop gdpPercap
##    <fct>       <fct>     <int>   <dbl>    <int>     <dbl>
##  1 Afghanistan Asia       1952    28.8  8425333      779.
##  2 Afghanistan Asia       1957    30.3  9240934      821.
##  3 Afghanistan Asia       1962    32.0 10267083      853.
##  4 Afghanistan Asia       1967    34.0 11537966      836.
##  5 Afghanistan Asia       1972    36.1 13079460      740.
##  6 Afghanistan Asia       1977    38.4 14880372      786.
##  7 Afghanistan Asia       1982    39.9 12881816      978.
##  8 Afghanistan Asia       1987    40.8 13867957      852.
##  9 Afghanistan Asia       1992    41.7 16317921      649.
## 10 Afghanistan Asia       1997    41.8 22227415      635.
## # ... with 1,694 more rows
gapminder %>% 
  select(country, year, lifeExp)
## # A tibble: 1,704 x 3
##    country      year lifeExp
##    <fct>       <int>   <dbl>
##  1 Afghanistan  1952    28.8
##  2 Afghanistan  1957    30.3
##  3 Afghanistan  1962    32.0
##  4 Afghanistan  1967    34.0
##  5 Afghanistan  1972    36.1
##  6 Afghanistan  1977    38.4
##  7 Afghanistan  1982    39.9
##  8 Afghanistan  1987    40.8
##  9 Afghanistan  1992    41.7
## 10 Afghanistan  1997    41.8
## # ... with 1,694 more rows
gapminder %>% 
  select(country, lifeExp:gdpPercap)
## # A tibble: 1,704 x 4
##    country     lifeExp      pop gdpPercap
##    <fct>         <dbl>    <int>     <dbl>
##  1 Afghanistan    28.8  8425333      779.
##  2 Afghanistan    30.3  9240934      821.
##  3 Afghanistan    32.0 10267083      853.
##  4 Afghanistan    34.0 11537966      836.
##  5 Afghanistan    36.1 13079460      740.
##  6 Afghanistan    38.4 14880372      786.
##  7 Afghanistan    39.9 12881816      978.
##  8 Afghanistan    40.8 13867957      852.
##  9 Afghanistan    41.7 16317921      649.
## 10 Afghanistan    41.8 22227415      635.
## # ... with 1,694 more rows
gapminder %>% 
  select(-continent)
## # A tibble: 1,704 x 5
##    country      year lifeExp      pop gdpPercap
##    <fct>       <int>   <dbl>    <int>     <dbl>
##  1 Afghanistan  1952    28.8  8425333      779.
##  2 Afghanistan  1957    30.3  9240934      821.
##  3 Afghanistan  1962    32.0 10267083      853.
##  4 Afghanistan  1967    34.0 11537966      836.
##  5 Afghanistan  1972    36.1 13079460      740.
##  6 Afghanistan  1977    38.4 14880372      786.
##  7 Afghanistan  1982    39.9 12881816      978.
##  8 Afghanistan  1987    40.8 13867957      852.
##  9 Afghanistan  1992    41.7 16317921      649.
## 10 Afghanistan  1997    41.8 22227415      635.
## # ... with 1,694 more rows
gapminder %>% 
  select(continent, country, year:gdpPercap) #switch continent and country
## # A tibble: 1,704 x 6
##    continent country      year lifeExp      pop gdpPercap
##    <fct>     <fct>       <int>   <dbl>    <int>     <dbl>
##  1 Asia      Afghanistan  1952    28.8  8425333      779.
##  2 Asia      Afghanistan  1957    30.3  9240934      821.
##  3 Asia      Afghanistan  1962    32.0 10267083      853.
##  4 Asia      Afghanistan  1967    34.0 11537966      836.
##  5 Asia      Afghanistan  1972    36.1 13079460      740.
##  6 Asia      Afghanistan  1977    38.4 14880372      786.
##  7 Asia      Afghanistan  1982    39.9 12881816      978.
##  8 Asia      Afghanistan  1987    40.8 13867957      852.
##  9 Asia      Afghanistan  1992    41.7 16317921      649.
## 10 Asia      Afghanistan  1997    41.8 22227415      635.
## # ... with 1,694 more rows
gapminder %>% 
  select(kontinent = continent, land = country, jahr = year)
## # A tibble: 1,704 x 3
##    kontinent land         jahr
##    <fct>     <fct>       <int>
##  1 Asia      Afghanistan  1952
##  2 Asia      Afghanistan  1957
##  3 Asia      Afghanistan  1962
##  4 Asia      Afghanistan  1967
##  5 Asia      Afghanistan  1972
##  6 Asia      Afghanistan  1977
##  7 Asia      Afghanistan  1982
##  8 Asia      Afghanistan  1987
##  9 Asia      Afghanistan  1992
## 10 Asia      Afghanistan  1997
## # ... with 1,694 more rows

the arrange verb

gapminder %>% 
  arrange(gdpPercap)
## # A tibble: 1,704 x 6
##    country          continent  year lifeExp      pop gdpPercap
##    <fct>            <fct>     <int>   <dbl>    <int>     <dbl>
##  1 Congo, Dem. Rep. Africa     2002    45.0 55379852      241.
##  2 Congo, Dem. Rep. Africa     2007    46.5 64606759      278.
##  3 Lesotho          Africa     1952    42.1   748747      299.
##  4 Guinea-Bissau    Africa     1952    32.5   580653      300.
##  5 Congo, Dem. Rep. Africa     1997    42.6 47798986      312.
##  6 Eritrea          Africa     1952    35.9  1438760      329.
##  7 Myanmar          Asia       1952    36.3 20092996      331 
##  8 Lesotho          Africa     1957    45.0   813338      336.
##  9 Burundi          Africa     1952    39.0  2445618      339.
## 10 Eritrea          Africa     1957    38.0  1542611      344.
## # ... with 1,694 more rows
gapminder %>% 
  arrange(desc(gdpPercap))
## # A tibble: 1,704 x 6
##    country   continent  year lifeExp     pop gdpPercap
##    <fct>     <fct>     <int>   <dbl>   <int>     <dbl>
##  1 Kuwait    Asia       1957    58.0  212846   113523.
##  2 Kuwait    Asia       1972    67.7  841934   109348.
##  3 Kuwait    Asia       1952    55.6  160000   108382.
##  4 Kuwait    Asia       1962    60.5  358266    95458.
##  5 Kuwait    Asia       1967    64.6  575003    80895.
##  6 Kuwait    Asia       1977    69.3 1140357    59265.
##  7 Norway    Europe     2007    80.2 4627926    49357.
##  8 Kuwait    Asia       2007    77.6 2505559    47307.
##  9 Singapore Asia       2007    80.0 4553009    47143.
## 10 Norway    Europe     2002    79.0 4535591    44684.
## # ... with 1,694 more rows
gapminder %>% 
  arrange(year, gdpPercap)
## # A tibble: 1,704 x 6
##    country           continent  year lifeExp       pop gdpPercap
##    <fct>             <fct>     <int>   <dbl>     <int>     <dbl>
##  1 Lesotho           Africa     1952    42.1    748747      299.
##  2 Guinea-Bissau     Africa     1952    32.5    580653      300.
##  3 Eritrea           Africa     1952    35.9   1438760      329.
##  4 Myanmar           Asia       1952    36.3  20092996      331 
##  5 Burundi           Africa     1952    39.0   2445618      339.
##  6 Ethiopia          Africa     1952    34.1  20860941      362.
##  7 Cambodia          Asia       1952    39.4   4693836      368.
##  8 Malawi            Africa     1952    36.3   2917802      369.
##  9 Equatorial Guinea Africa     1952    34.5    216964      376.
## 10 China             Asia       1952    44   556263527      400.
## # ... with 1,694 more rows

the mutate verb

existing and new variables

gapminder %>% 
  mutate(pop_mio = pop / 1000000) %>% 
  mutate(gdp = gdpPercap * pop)
## # A tibble: 1,704 x 8
##    country    continent  year lifeExp     pop gdpPercap pop_mio        gdp
##    <fct>      <fct>     <int>   <dbl>   <int>     <dbl>   <dbl>      <dbl>
##  1 Afghanist~ Asia       1952    28.8  8.43e6      779.    8.43    6.57e 9
##  2 Afghanist~ Asia       1957    30.3  9.24e6      821.    9.24    7.59e 9
##  3 Afghanist~ Asia       1962    32.0  1.03e7      853.   10.3     8.76e 9
##  4 Afghanist~ Asia       1967    34.0  1.15e7      836.   11.5     9.65e 9
##  5 Afghanist~ Asia       1972    36.1  1.31e7      740.   13.1     9.68e 9
##  6 Afghanist~ Asia       1977    38.4  1.49e7      786.   14.9     1.17e10
##  7 Afghanist~ Asia       1982    39.9  1.29e7      978.   12.9     1.26e10
##  8 Afghanist~ Asia       1987    40.8  1.39e7      852.   13.9     1.18e10
##  9 Afghanist~ Asia       1992    41.7  1.63e7      649.   16.3     1.06e10
## 10 Afghanist~ Asia       1997    41.8  2.22e7      635.   22.2     1.41e10
## # ... with 1,694 more rows

total GDP now spaces only one word

gapminder %>% 
  mutate(gdp = gdpPercap * pop) %>% 
  arrange(gdp)
## # A tibble: 1,704 x 7
##    country              continent  year lifeExp    pop gdpPercap       gdp
##    <fct>                <fct>     <int>   <dbl>  <int>     <dbl>     <dbl>
##  1 Sao Tome and Princi~ Africa     1952    46.5  60011      880.    5.28e7
##  2 Sao Tome and Princi~ Africa     1957    48.9  61325      861.    5.28e7
##  3 Sao Tome and Princi~ Africa     1962    51.9  65345     1072.    7.00e7
##  4 Equatorial Guinea    Africa     1952    34.5 216964      376.    8.15e7
##  5 Sao Tome and Princi~ Africa     1967    54.4  70787     1385.    9.80e7
##  6 Equatorial Guinea    Africa     1957    36.0 232922      426.    9.92e7
##  7 Sao Tome and Princi~ Africa     1972    56.5  76595     1533.    1.17e8
##  8 Gambia               Africa     1952    30   284320      485.    1.38e8
##  9 Equatorial Guinea    Africa     1962    37.5 249220      583.    1.45e8
## 10 Sao Tome and Princi~ Africa     1977    58.6  86796     1738.    1.51e8
## # ... with 1,694 more rows

Combining with pipes

Assigning new “objects”

Natürlich kann man die kompletten Ketten auch in einem neuen Objekt sichern.

gapminder2 <- gapminder %>% 
  mutate(gdp = gdpPercap * pop) %>% 
  arrange(gdp)
gapminder2
## # A tibble: 1,704 x 7
##    country              continent  year lifeExp    pop gdpPercap       gdp
##    <fct>                <fct>     <int>   <dbl>  <int>     <dbl>     <dbl>
##  1 Sao Tome and Princi~ Africa     1952    46.5  60011      880.    5.28e7
##  2 Sao Tome and Princi~ Africa     1957    48.9  61325      861.    5.28e7
##  3 Sao Tome and Princi~ Africa     1962    51.9  65345     1072.    7.00e7
##  4 Equatorial Guinea    Africa     1952    34.5 216964      376.    8.15e7
##  5 Sao Tome and Princi~ Africa     1967    54.4  70787     1385.    9.80e7
##  6 Equatorial Guinea    Africa     1957    36.0 232922      426.    9.92e7
##  7 Sao Tome and Princi~ Africa     1972    56.5  76595     1533.    1.17e8
##  8 Gambia               Africa     1952    30   284320      485.    1.38e8
##  9 Equatorial Guinea    Africa     1962    37.5 249220      583.    1.45e8
## 10 Sao Tome and Princi~ Africa     1977    58.6  86796     1738.    1.51e8
## # ... with 1,694 more rows

the summarize verb

many rows into one

gapminder %>% 
  summarize(meanLifeExp = mean(lifeExp))
## # A tibble: 1 x 1
##   meanLifeExp
##         <dbl>
## 1        59.5

“mean()” ist eine built-in Funktion. Hier logischerweise der Mittelwert. R hat einige solcher built-in Funktionen, die man sich nicht selber schreiben muss

Beispiele bringen:

  • mean()
  • sum()
  • median()
  • min()
  • max()

Eigentlich natürlich keinen Sinn den Mittelwert über alles zu machen

gapminder %>%
  filter(year == 2007) %>%
  summarise(meanLifeExp = mean(lifeExp))
## # A tibble: 1 x 1
##   meanLifeExp
##         <dbl>
## 1        67.0

mehrere Spalten (Variablen gleichzeitig)

gapminder %>%
  filter(year == 2007) %>%
  summarise(meanLifeExp = mean(lifeExp),
            totalPop = sum(as.numeric(pop)))
## # A tibble: 1 x 2
##   meanLifeExp   totalPop
##         <dbl>      <dbl>
## 1        67.0 6251013179

the group_by verb

Ich möchte nicht die LifeExpectancy oder Population über alle Länder und alle Zeitpunkte Daher gruppiere ich den Datensatz in verschiedene Teile, basierend auf der Variable “year”

gapminder %>%
  group_by(year) %>%
  summarize(meanLifeExp = mean(lifeExp),
            totalPop = sum(pop))

Produziert bei mir Fehler (integer overflow), deshalb wie in Fehlermeldung vorgeschlagen “as.integer”. Innerhalb der Funktionen, lassen sich also wieder weitere Funktionen verschachteln

gapminder_3 <- gapminder %>%
  group_by(year) %>%
  summarize(meanLifeExp = mean(lifeExp),
            totalPop = sum(as.integer(pop)))

Jetzt finde ich das auch nicht besonders aussagekräftig. Bei dem Durchschnitt sind alle Ländern mit drin. Deshalb filtern nur für das Jahr 2007 und anschließend nach Kontinent.

gapminder %>%
  filter(year == 2007) %>%
  group_by(continent) %>%
  summarize(meanLifeExp = mean(lifeExp),
            totalPop = sum(as.numeric(pop)))
## # A tibble: 5 x 3
##   continent meanLifeExp   totalPop
##   <fct>           <dbl>      <dbl>
## 1 Africa           54.8  929539692
## 2 Americas         73.6  898871184
## 3 Asia             70.7 3811953827
## 4 Europe           77.6  586098529
## 5 Oceania          80.7   24549947

Jetzt wollen wir aber jeweils den Durchschnitt für alle Jahr und alle Kontinente. group_by lässt sich auch mit mehreren Variablen nutzen. Gruppierung nach mehreren Variablen.

gapminder %>%
  group_by(year, continent) %>%
  summarize(totalPop = sum(as.integer(pop)),
            meanLifeExp = mean(lifeExp))
## # A tibble: 60 x 4
## # Groups:   year [?]
##     year continent   totalPop meanLifeExp
##    <int> <fct>          <dbl>       <dbl>
##  1  1952 Africa     237640501        39.1
##  2  1952 Americas   345152446        53.3
##  3  1952 Asia      1395357351        46.3
##  4  1952 Europe     418120846        64.4
##  5  1952 Oceania     10686006        69.3
##  6  1957 Africa     264837738        41.3
##  7  1957 Americas   386953916        56.0
##  8  1957 Asia      1562780599        49.3
##  9  1957 Europe     437890351        66.7
## 10  1957 Oceania     11941976        70.3
## # ... with 50 more rows

Nach summarise ist die Gruppierung aufgehoben.

gapminder %>%
  group_by(year, continent) %>%
  summarize(totalPop = sum(as.integer(pop)),
            meanLifeExp = mean(lifeExp)) %>% 
  arrange(desc(totalPop))
## # A tibble: 60 x 4
## # Groups:   year [12]
##     year continent   totalPop meanLifeExp
##    <int> <fct>          <dbl>       <dbl>
##  1  2007 Asia      3811953827        70.7
##  2  2002 Asia      3601802203        69.2
##  3  1997 Asia      3383285500        68.0
##  4  1992 Asia      3133292191        66.5
##  5  1987 Asia      2871220762        64.9
##  6  1982 Asia      2610135582        62.6
##  7  1977 Asia      2384513556        59.6
##  8  1972 Asia      2150972248        57.3
##  9  1967 Asia      1905662900        54.7
## 10  1962 Asia      1696357182        51.6
## # ... with 50 more rows

Wenn ich aber zB arrange direkt nach group_by ausführe, dann werden die Gruppen weiter berücksichtigt -> Sortierung innerhalb von Gruppen.

gapminder %>%
  group_by(year, continent) %>%
  arrange(desc(pop))
## # A tibble: 1,704 x 6
## # Groups:   year, continent [60]
##    country continent  year lifeExp        pop gdpPercap
##    <fct>   <fct>     <int>   <dbl>      <int>     <dbl>
##  1 China   Asia       2007    73.0 1318683096     4959.
##  2 China   Asia       2002    72.0 1280400000     3119.
##  3 China   Asia       1997    70.4 1230075000     2289.
##  4 China   Asia       1992    68.7 1164970000     1656.
##  5 India   Asia       2007    64.7 1110396331     2452.
##  6 China   Asia       1987    67.3 1084035000     1379.
##  7 India   Asia       2002    62.9 1034172547     1747.
##  8 China   Asia       1982    65.5 1000281000      962.
##  9 India   Asia       1997    61.8  959000000     1459.
## 10 China   Asia       1977    64.0  943455000      741.
## # ... with 1,694 more rows

Durch anschließen von ungroup() kann ich die Gruppierung wieder aufheben.

Joins - Merging different datasets into one

  • left_join(x, y): Return all rows from x, and all columns from x and y. If there are multiple matches between x and y, all combination of the matches are returned. This is a mutating join.
  • right_join(x, y): Return all rows from y, and all columns from x and y. Rows in y with no match in x will have NA values in the new columns. If there are multiple matches between x and y, all combinations of the matches are returned.
  • full_join(x, y): Return all rows and all columns from both x and y. Where there are not matching values, returns NA for the one missing. This is a mutating join.
  • inner_join(x, y): Return all rows from x where there are matching values in y, and all columns from x and y. If there are multiple matches between x and y, all combination of the matches are returned. This is a mutating join.
  • semi_join(x, y): Return all rows from x where there are matching values in y, keeping just columns from x. A semi join differs from an inner join because an inner join will return one row of x for each matching row of y, where a semi join will never duplicate rows of x. This is a filtering join.
  • anti_join(x, y): Return all rows from x where there are not matching values in y, keeping just columns from x. This is a filtering join.

Visualising with ggplot2

library(ggplot2)

ggplot2 von Hadley Wickham auch hier eine eigene “Grammatik” Modular aufgebaut (Bedeutet was? - add a layer)

Ein neuer Datensatz wurde durch erstellt: gapminder_2007. Durch die filter-Funktion enthält er nur die Daten aus dem Jahr 2007.

gapminder_2007
## # A tibble: 142 x 6
##    country     continent  year lifeExp       pop gdpPercap
##    <fct>       <fct>     <int>   <dbl>     <int>     <dbl>
##  1 Afghanistan Asia       2007    43.8  31889923      975.
##  2 Albania     Europe     2007    76.4   3600523     5937.
##  3 Algeria     Africa     2007    72.3  33333216     6223.
##  4 Angola      Africa     2007    42.7  12420476     4797.
##  5 Argentina   Americas   2007    75.3  40301927    12779.
##  6 Australia   Oceania    2007    81.2  20434176    34435.
##  7 Austria     Europe     2007    79.8   8199783    36126.
##  8 Bahrain     Asia       2007    75.6    708573    29796.
##  9 Bangladesh  Asia       2007    64.1 150448339     1391.
## 10 Belgium     Europe     2007    79.4  10392226    33693.
## # ... with 132 more rows
ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp))

ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp))+
  geom_point()

ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp))+
  geom_point()+
  geom_line()

ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp))+
  geom_point()+
  geom_line()+
  geom_smooth(method = 'lm')

Add log scales

ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp))+
  geom_point()

Problem: Viele Länder am linken Rand, mit sehr geringem gdpPercap Lösungsmöglichkeit: Log Scale (Modularer Aufbau - Hinzufügen eines “Moduls” log_scale)

ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp))+
  geom_point()+
  scale_x_log10()

ggplot(gapminder_2007, aes(x = pop, y = gdpPercap))+
  geom_point()+
  scale_x_log10()+
  scale_y_log10()

Adding trend lines

ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp))+
  geom_point()+
  scale_x_log10()+
  geom_smooth()
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Additional aesthetics

Bisher hatten wir nur x und y Mit aesthetics (aes) lassen sich aber auch noch mehr Merkmale kontrollieren Farbe, Gruppen, Punktgröße etc.

Automatisches Hinzufügen der Legende

ggplot(gapminder_2007) +
  geom_point(aes(x = gdpPercap, y = lifeExp, color = continent)) +
  scale_x_log10()

Notes: Zweite Zeile bei size, macht dem Code nichts aus. Nach Kommata wird sogar einigermaßen schön eingerückt

ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp, 
                           color = continent, 
                           size = pop)) +
  geom_point() +
  scale_x_log10()

Faceting

Unterteilung in “Untergrafiken”, unterteilt nach einer bestimmten Kategorie

ggplot(gapminder_2007, aes(x = gdpPercap, y = lifeExp)) +
  geom_point() +
  scale_x_log10() +
  facet_wrap(~ continent)

ggplot(gapminder, aes(x = gdpPercap, y = lifeExp, color = lifeExp, size = pop))+
  geom_point()+
  scale_x_log10()+
  facet_wrap(~ year)+
  scale_color_viridis()

Neues Objekt (Datensatz speichern): gapminder gruppert nach Jahr und die Population und durchschnittliche Lebenserwartung pro Jahr zusammengefasst.

by_year <- gapminder %>%
  group_by(year) %>%
  summarize(totalPop = sum(as.integer(pop)),
            meanLifeExp = mean(lifeExp))

by_year
## # A tibble: 12 x 3
##     year   totalPop meanLifeExp
##    <int>      <dbl>       <dbl>
##  1  1952 2406957150        49.1
##  2  1957 2664404580        51.5
##  3  1962 2899782974        53.6
##  4  1967 3217478384        55.7
##  5  1972 3576977158        57.6
##  6  1977 3930045807        59.6
##  7  1982 4289436840        61.5
##  8  1987 4691477418        63.2
##  9  1992 5110710260        64.2
## 10  1997 5515204472        65.0
## 11  2002 5886977579        65.7
## 12  2007 6251013179        67.0
ggplot(by_year, aes(x = year, y = totalPop)) +
  geom_point()

Hier enthält die y-Achse nicht die 0 (Meistens großer Fehler). Wir müssen deshalb die Skala bearbeiten und anpassen. Wieder kann dies durch ein neues “Modul” passieren.

ggplot(by_year, aes(x = year, y = totalPop)) +
  geom_point() +
  expand_limits(y = 0)

Neues Objekt (Datensatz) mit einer Gruppierung nach Year und continent.

by_year_continent <- gapminder %>%
  group_by(year, continent) %>%
  summarize(totalPop = sum(as.numeric(pop)),
            meanLifeExp = mean(lifeExp))

by_year_continent
## # A tibble: 60 x 4
## # Groups:   year [?]
##     year continent   totalPop meanLifeExp
##    <int> <fct>          <dbl>       <dbl>
##  1  1952 Africa     237640501        39.1
##  2  1952 Americas   345152446        53.3
##  3  1952 Asia      1395357351        46.3
##  4  1952 Europe     418120846        64.4
##  5  1952 Oceania     10686006        69.3
##  6  1957 Africa     264837738        41.3
##  7  1957 Americas   386953916        56.0
##  8  1957 Asia      1562780599        49.3
##  9  1957 Europe     437890351        66.7
## 10  1957 Oceania     11941976        70.3
## # ... with 50 more rows

Durch Farbe können wir wieder die verschiedenen Kontinenten voneinander trennen.

ggplot(by_year_continent, aes(x = year, y = totalPop, color = continent)) +
  geom_point() +
  expand_limits(y = 0)+
  scale_color_viridis(discrete = T)

Bisher nur “Scatterplots”, mit geom_point(). Jede Menge andere Varianten ebenso möglich. Wahl des Graphen abhängig von dem Skalenniveau der Daten und dem Ziel, was die Grafik zeigen soll.

Line Plots

ggplot(by_year_continent, aes(x = year, y = meanLifeExp, color = continent)) +
  geom_point() +
  expand_limits(y = 0)

ggplot(by_year_continent, aes(x = year, y = meanLifeExp, color = continent)) +
  geom_line() +
  expand_limits(y = 0)

Man kann aber auch mehrere Graphtypen miteinander verbinden. Wieder durch die modulare “Grammatik” des Pakets.

ggplot(by_year_continent, aes(x = year, y = meanLifeExp, color = continent)) +
  geom_line() +
  geom_point() +
  expand_limits(y = 0)

Barplots

Neuer Datensatz mit der durchschnittlichen Lebenserwartung pro Kontinent für das Jahr 2007

by_continent <- gapminder %>%
  filter(year == 2007) %>%
  group_by(continent) %>%
  summarize(meanLifeExp = mean(lifeExp))

by_continent
## # A tibble: 5 x 2
##   continent meanLifeExp
##   <fct>           <dbl>
## 1 Africa           54.8
## 2 Americas         73.6
## 3 Asia             70.7
## 4 Europe           77.6
## 5 Oceania          80.7

Unerwarterweise nicht geom_bar. Das gibts aber auch. Hier geom_col. Bei geom_bar könnte man das gleiche Ergebnis erreichen, müsste aber noch zusätzliche Argumente anfügen.

ggplot(by_continent, aes(x = continent, y = meanLifeExp)) +
  geom_col()

Histogram

Nur ein “aesthetic”. Die x-Variable. Die Anzahl pro Balken rechnet R dann selber aus. Auch die Breite der Balken wir selbst optimiert. Diese kann man aber anpassen.

ggplot(gapminder_2007, aes(x = lifeExp)) +
  geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

ggplot(gapminder_2007, aes(x = lifeExp)) +
  geom_histogram(binwidth = 5)

Boxplots

Compare distributions across continents.

Black Line: Median, Box: 25% and 75%. Half of the distribution inside the box. whiskers: Additional countries Dots: Outliers (out of 95%)

ggplot(gapminder_2007, aes(x = continent, y = lifeExp)) +
  geom_point()

ggplot(gapminder_2007, aes(x = continent, y = lifeExp)) +
  geom_boxplot()

Labels

ggplot(gapminder_2007, aes(x = continent, y = gdpPercap)) +
  geom_boxplot() +
  scale_y_log10() + 
  labs(title = "Comparing GDP per capita across continents",
       x = "Continent",
       y = "GDP per capita")